package com.ganbo.thread.threadSafe;

/**
 * Created by gan on 2020/5/19 8:39.
 */
public class ThreadUnSafeDemo extends Thread {

    private ShareResource shareResource;

    @Override
    public void run() {
        try {
            if (Thread.currentThread().getName().equals("a")) {
                shareResource.setNumber("a");
            } else {
                shareResource.setNumber("b");
            }
        } catch (Exception e) {

        }

    }

    public ThreadUnSafeDemo(ShareResource shareResource) {
        this.shareResource = shareResource;
    }

    public static void main(String[] args) {

        ShareResource shareResource = new ShareResource();

        ThreadUnSafeDemo a = new ThreadUnSafeDemo(shareResource);
        a.setName("a");

        ThreadUnSafeDemo b = new ThreadUnSafeDemo(shareResource);
        b.setName("b");

        a.start();
        b.start();
    }

}

class ShareResource {

    private int number;

    public synchronized void setNumber(String name) throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + " set start...");

        if ("a".equals(name)) {
            number = 100;
            Thread.sleep(1000);
        } else {
            number = 200;
        }
        System.out.println(Thread.currentThread().getName() + " set end.....number===>" + number);
    }

}

